package client;

import javax.swing.*;


import java.awt.event.*;
import java.awt.*;
import java.io.*;

public class Frame extends JFrame implements ActionListener{
	private GuiClient nap;
	private Dimension frameSize = new Dimension( 575, 280 );
	private JScrollPane scroll;
	protected JTextArea display;
	protected JTextField input;
	protected JButton connect;
	protected JButton quit;
	protected JButton retr;
	protected JButton query;
	PrintStream print =
		new PrintStream(
				new FilteredStream(
						new ByteArrayOutputStream()));
	
	public Frame( GuiClient nap ){
		super( "Client for Robot" );
		setSize( frameSize );
		this.nap = nap;
		Container c = getContentPane();
		
		display = new JTextArea(12,60);
		display.setEditable(false);
		display.setFont(new Font(null,Font.PLAIN, 10 ));
		input	= new JTextField(49);
		scroll = new JScrollPane();
		scroll.getViewport().add(display);
		

		connect = new JButton( "CONNECT" );
		connect.addActionListener(this);
		quit	= new JButton( "QUIT" );
		quit.addActionListener(this);
		retr= new JButton( "RETR" );
		retr.addActionListener(this);
		query	= new JButton( "QUERY" );
		query.addActionListener(this);
		JPanel center	= new JPanel(new FlowLayout());
		
		center.add(scroll);
		center.add(input);
		center.add(connect);
		center.add(query);
		center.add(retr);
		center.add(quit);
		
		c.add(BorderLayout.CENTER, center);

		input.requestFocus();
		setLocationRelativeTo(null);
		setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		System.setOut(print);
		System.setErr(print);
		
		query.setEnabled(false);
		retr.setEnabled(false);
	}
	public void actionPerformed(ActionEvent e) {
		String line = e.getActionCommand() + " " + input.getText();
		input.setText("");
		display.setText("");
		display.append("\n" + line);
		nap.handleGui(line);
	}

	public static void main( String[] args ){
		Frame win = new Frame(null);
		win.setVisible(true);
	}
	
	class FilteredStream extends FilterOutputStream 
	{
		public FilteredStream(OutputStream aStream){
			super(aStream);
		}
		
		public void write(byte b[]) throws IOException {
			String aString = new String(b);
			display.append(aString);
		}
		
		public void write(byte b[], int off, int len ){
			String aString = new String(b , off, len);
			display.append(aString);
		}
	}
}
